package com.javatiaocao.myblog.controller;

import com.javatiaocao.myblog.constant.CodeType;
import com.javatiaocao.myblog.model.LeaveMessage;
import com.javatiaocao.myblog.service.LeaveWordService;
import com.javatiaocao.myblog.utils.DataMap;
import com.javatiaocao.myblog.utils.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class LeaveWordController {

    @Autowired
    private LeaveWordService leaveWordService;

    /**
     *
     * 获取页面留言信息/getPageLeaveMessage
     */
    @GetMapping("/getPageLeaveMessage")
    public String getPageLeaveMessage(String pageName) {
        try {
            DataMap dataMap = leaveWordService.getPageLeaveMessage(pageName);
            return JsonResult.build(dataMap).toJSON();

        }catch (Exception e){
            log.error("getPageLeaveMessage is error"+e);
        }
        return JsonResult.fail(CodeType.SERVER_EXCEPTION).toJSON();
    }


    /**
     *
     * 发表留言
     * @param leaveMessage
     * @return
     */
    @PostMapping("/publishLeaveMessage")
    public String publishLeaveMessage(LeaveMessage leaveMessage ,String parentId,String respondent,@AuthenticationPrincipal UserDetails userDetails) {
        try {
            if (parentId == null || parentId.equals("")) {
                parentId = "0";
            }
            if (respondent == null || respondent.equals("")) {
                respondent = "0";
            }
            DataMap dataMap = leaveWordService.publishLeaveMessage(leaveMessage,parentId,respondent,userDetails);
            return JsonResult.build(dataMap).toJSON();

        }catch (Exception e){
            log.error("publishLeaveMessage is error"+e);
        }
        return JsonResult.fail(CodeType.SERVER_EXCEPTION).toJSON();
    }
}
